package com.study.component.mybatis;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement.ValuesClause;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author tanglingyu
 * @Date: 2021/07/01/ 15:30
 * @Description
 */
@Slf4j
public class MyBatisVisitor extends MySqlASTVisitorAdapter {

  private static final String[] TABLES = {"my_user"};

  @Override
  public boolean visit(MySqlInsertStatement x) {
    SQLName tableName = x.getTableName();

    boolean include = Arrays.stream(TABLES)
        .anyMatch(
            data -> StringUtils.equalsIgnoreCase(tableName.getSimpleName().replace("`", ""), data));

    if (!include) {
      return true;
    }

    log.debug("改写数据库{}", tableName.getSimpleName());
    // 如果sql中包含了sb,跳过修改
    if (x.getColumns().contains(SQLUtils.toMySqlExpr("sb"))) {
      return true;
    }
    x.addColumn(SQLUtils.toMySqlExpr("sb"));
    StringBuilder builder = new StringBuilder("'").append("sb_tang")
        .append("'");
    String valueSql = builder.toString();

    for (ValuesClause valuesClause : x.getValuesList()) {
      valuesClause.addValue(SQLUtils.toMySqlExpr(valueSql));
    }
    return true;
  }

}

